package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnLoadmoreListener;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnScrollListener1;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.bean.NearByInfo;
import com.xindaoapp.happypet.bean.NearPictureBean;
import com.xindaoapp.happypet.bean.NearPictureBean.SplashPicture;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.RollViewPager;
import com.xindaoapp.happypet.view.RoundImageView2;

/**
 * 首页--活动fragment
 * 
 * @author Yangqing
 * 
 */
public class NearByFragment extends BaseFragment {

    private PullToRefreshStaggeredGridView pullRefreshStagGridView;
    private Activity mContext;
    private int count;
    private int currentPage = 1;
    private GridListAdapter pictureAdapter;
    private View mHeadView;
    private LinearLayout mViewPagerContainer, mPointsContainer;
    private TextView mTvDescription;
    private List<NearByInfo> mBanners;
    private ArrayList<View> mDotLists;
    private RollViewPager mRollViewPager;
    private TextView rightTextView;

    public enum LoadType {
        // PULLDOWN 下拉刷新
        // PULLUP 上拉加载
        PULLDOWN, PULLUP
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.mContext = getActivity();
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.layout_nearby, null);
    }

    @Override
    protected void initViews() {
        super.initViews();

        TextView top_bar_title = (TextView) getView().findViewById(R.id.top_bar_title);
        rightTextView = (TextView) getView().findViewById(R.id.top_bar_right_textview);
        top_bar_title.setText("晒图活动");
        rightTextView.setText("我参加的");
        // rightTextView.setVisibility(View.GONE);
        rightTextView.setClickable(false);

        pullRefreshStagGridView =
                (PullToRefreshStaggeredGridView) getView().findViewById(
                        R.id.pullRefreshStagGridView);
        pullRefreshStagGridView.setMode(PullToRefreshBase.Mode.BOTH);
        pullRefreshStagGridView.getRefreshableView().setColumnCount(2);
        pullRefreshStagGridView.setVisibility(View.GONE);

        mHeadView = LayoutInflater.from(mContext).inflate(R.layout.head_zuixinfragment, null);
        mViewPagerContainer = (LinearLayout) mHeadView.findViewById(R.id.viewpager1);
        mViewPagerContainer.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth * 248 / 640));
        mTvDescription = (TextView) mHeadView.findViewById(R.id.tv_image_description1);
        mPointsContainer = (LinearLayout) mHeadView.findViewById(R.id.ll_points1);


        View foot = View.inflate(mContext, R.layout.layout_loading_footer, null);
        pullRefreshStagGridView.getRefreshableView().setFooterView(foot);
        pullRefreshStagGridView.getRefreshableView().getFooterView().setVisibility(View.GONE);
        pullRefreshStagGridView.getRefreshableView().setHeaderView(mHeadView);
        pullRefreshStagGridView.getRefreshableView().setAdapter(null);
        pullRefreshStagGridView.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
                pullRefreshStagGridView.getRefreshableView().setColumnCount(2);
                if (CommonUtil.isNetworkAvailable(mContext) == 0) {
                    Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    pullRefreshStagGridView.onRefreshComplete();
                    return;
                }
                currentPage = 1;
                // getGridViewData(LoadType.PULLDOWN);
                loadDatas();

            }


        });
        pullRefreshStagGridView.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore() {
                if (CommonUtil.isNetworkAvailable(mContext) == 0) {
                    Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    pullRefreshStagGridView.onRefreshComplete();
                    return;
                }

                if (count > (currentPage * 16 - 1)) {
                    pullRefreshStagGridView.getRefreshableView().getFooterView()
                            .setVisibility(View.VISIBLE);
                    currentPage++;
                    getGridViewData(LoadType.PULLUP);
                } else {
                    pullRefreshStagGridView.getRefreshableView().getFooterView()
                            .setVisibility(View.GONE);
                }

                pullRefreshStagGridView.onRefreshComplete();
            }
        });

        pullRefreshStagGridView.getRefreshableView().setOnScrollListener1(new OnScrollListener1() {

            @Override
            public void onScoll(int first) {

            }
        });

    }

    @Override
    protected void initEvents() {
        super.initEvents();
        rightTextView.setOnClickListener(mOnClickListener);

    }

    @Override
    protected void loadDatas() {
        super.loadDatas();

        getBannerData();
        getGridViewData(LoadType.PULLDOWN);
    }

    /**
     * 获取banner数据
     */
    private void getBannerData() {
        getMoccaApi().getNearByInfo(new IRequest<List<NearByInfo>>() {

            @Override
            public void request(List<NearByInfo> t) {

                if (null != t) {
                    // onDataArrived(true);
                    if (t.size() == 0) {
                        // onDataArrivedEmpty();
                    } else {
                        mBanners = t;
                        prepareViewPage(mContext, mBanners);
                    }
                } else {
                    onDataArrived(false);
                }
            }
        });

    }

    /**
     * 获取瀑布流数据
     */
    private void getGridViewData(final LoadType type) {

        getMoccaApi().getNearPicList(currentPage, 16, new IRequest<NearPictureBean>() {

            @Override
            public void request(NearPictureBean t) {
                pullRefreshStagGridView.onRefreshComplete();
                pullRefreshStagGridView.getRefreshableView().getFooterView()
                        .setVisibility(View.GONE);
                if (t != null && t.array != null) {
                    rightTextView.setClickable(true);
                    onDataArrived(true);
                    if (pullRefreshStagGridView.getVisibility() == View.GONE) {
                        pullRefreshStagGridView.setVisibility(View.VISIBLE);
                    }
                    count = Integer.parseInt(t.total);
                    if (type == LoadType.PULLDOWN) {
                        if (pictureAdapter == null) {
                            pictureAdapter = new GridListAdapter(t.array);
                            pullRefreshStagGridView.getRefreshableView().setAdapter(pictureAdapter);
                        } else {
                            pictureAdapter.clearItem();
                            pictureAdapter.addItem(t.array);
                        }
                    } else {
                        pictureAdapter.addItem(t.array);
                    }
                    pictureAdapter.notifyDataSetChanged();
                } else {
                    if (type == LoadType.PULLDOWN) {
                        onDataArrived(false);
                    }
                    pullRefreshStagGridView.onRefreshComplete();
                }
            }
        });
    }


    public void prepareViewPage(final Context context, final List<NearByInfo> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (NearByInfo homeBanner : list) {
            titleList.add(homeBanner.title);
            imageUrlList.add(homeBanner.coverpath);
        }
        initDots(list.size());
        mRollViewPager =
                new RollViewPager(context, mDotLists, R.drawable.banner_normal,
                        R.drawable.banner_selected, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {

                                if ("shaitu".equals(list.get(position).type)) {
                                    Intent intent =
                                            new Intent(mContext, SplashPictureActivity2.class);
                                    intent.putExtra("actID", list.get(position).link);
                                    startActivity(intent);
                                }
                            }
                        });
        mRollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        mRollViewPager.setTitle(mTvDescription, titleList);
        mRollViewPager.setImageUrl(imageUrlList);
        mRollViewPager.startRoll();
        mViewPagerContainer.removeAllViews();
        mViewPagerContainer.addView(mRollViewPager);

    }

    private void initDots(int size) {
        mDotLists = new ArrayList<View>();
        mPointsContainer.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext, 5),
                            CommonUtil.dip2px(mContext, 5));
            layoutParams.setMargins(5, 0, 5, 8);
            ImageView m = new ImageView(mContext);
            if (i == 0) {
                m.setBackgroundResource(R.drawable.banner_selected);
            } else {
                m.setBackgroundResource(R.drawable.banner_normal);
            }
            m.setLayoutParams(layoutParams);
            mDotLists.add(m);
            mPointsContainer.addView(m);
        }
    }


    public class GridListAdapter extends BaseAdapter {

        private List<SplashPicture> picList = new ArrayList<SplashPicture>();

        public GridListAdapter(List<SplashPicture> iniData) {
            this.picList = iniData;
        }

        public void clearItem() {
            if (picList != null) {
                picList.clear();
            }
        }

        public void addItem(List<SplashPicture> list) {
            this.picList.addAll(list);
        }

        @Override
        public int getCount() {
            if (picList == null) {
                return 0;
            } else {
                return picList.size();
            }
        }

        @SuppressLint("InlinedApi")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.item_splash_picture, null);
                holder.imageView = (RoundImageView2) convertView.findViewById(R.id.imageView);
                holder.iv_status = (ImageView) convertView.findViewById(R.id.iv_status);

                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.title.getBackground().setAlpha(100);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.iv_status.setVisibility(View.GONE);
            final SplashPicture splashPicture = picList.get(position);
            int mHeight = Integer.parseInt(splashPicture.coverheight);
            int mWidth = Integer.parseInt(splashPicture.coverwidth);

            holder.imageView.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, (int) ((float) CommonParameter.sScreenWidth / 2
                            / mWidth * mHeight)));
            if (!TextUtils.isEmpty(splashPicture.coverpath)) {
                ImageLoader.getInstance().displayImage(splashPicture.coverpath, holder.imageView);
            } else {
                holder.imageView.setBackgroundResource(R.drawable.picture_loading);
            }
            holder.title.setText(splashPicture.tag);

            holder.iv_status.setVisibility(View.VISIBLE);

            // 是比赛时，显示当前比赛是进行中还是已结束，不显示未开始比赛
            if (Constants.TYPE_GAME.equals(splashPicture.type)) {
                if (Constants.AVTIVITY_CHAGNQI.equals(splashPicture.status)) {
                    holder.iv_status.setVisibility(View.GONE);
                    // 长期活动不做任何处理
                    // holder.iv_status.setVisibility(View.VISIBLE);
                    // holder.iv_status.setBackgroundResource(R.drawable.activity_going);
                } else if (Constants.AVTIVITY_GOING.equals(splashPicture.status)) {
                    holder.iv_status.setBackgroundResource(R.drawable.activity_going);
                } else if (Constants.AVTIVITY_UNSTART.equals(splashPicture.status)) {
                    holder.iv_status.setBackgroundResource(R.drawable.activity_yugao);
                } else if (Constants.AVTIVITY_COMPLETE.equals(splashPicture.status)) {
                    holder.iv_status.setBackgroundResource(R.drawable.activity_finish);
                }
            }
            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (Constants.AVTIVITY_CHAGNQI.equals(splashPicture.status)
                            || Constants.AVTIVITY_GOING.equals(splashPicture.status)
                            || Constants.AVTIVITY_COMPLETE.equals(splashPicture.status)) {
                        Intent intent = new Intent(mContext, SplashPictureActivity2.class);
                        intent.putExtra("actID", picList.get(position).actid);
                        intent.putExtra("tagID", picList.get(position).tagid);
                        startActivity(intent);
                    } else if (Constants.AVTIVITY_UNSTART.equals(splashPicture.status)) {
                        // CommonUtil.loadHTML5(getActivity(),);
                        loadHTML5(splashPicture.htmlurl);
                    }

                }
            });

            return convertView;
        }

        @Override
        public Object getItem(int position) {
            return picList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        private class ViewHolder {
            RoundImageView2 imageView;
            TextView title;
            ImageView iv_status;

        }
    }

    /**
     * 加载更多的H5页面
     * 
     * @param htmlurl
     */
    private void loadHTML5(String htmlurl) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra(Constants.KEY_VIDEO_URL, htmlurl);
        intent.putExtra(Constants.KEY_TOP_BAR_TITLE, "活动详情");
        startActivity(intent);
    }


    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.top_bar_right_textview:
                    if (UserState.isLogged(getActivity()))
                        mContext.startActivity(new Intent(mContext, MyJoinInActivity.class));
                    break;
            }

        }

    };


}
